package com.ben.utils.ext

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

/**
 * @author bin.yang
 * @date 2019/11/25
 * @maintainer bin.yang
 * @copyright 2019 Inc. All rights reserved.
 * @desc:
 */
fun Any.toJson(): String? {
    return try {
        Gson().toJson(this)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

inline fun <reified T> String.toJsonList(): MutableList<T>? {
    return try {
        Gson().fromJson(this, object : TypeToken<MutableList<T>>() {}.type)
    } catch (e: Exception) {
        e.printStackTrace()
        arrayListOf()
    }
}

fun <T> String.fromJson(cls: Type): T? {
    try {
        return Gson().fromJson<T>(this, cls)
    } catch (e: Throwable) {
        e.printStackTrace()
    }
    return null
}
